<template>
  <div class="addEdit">
    <el-form ref="form" label-width="120px" :model="form" :rules="rules" inline>
      <el-form-item label="资金方" prop="fundCode">
        <el-select v-model="form.fundCode" placeholder="请选择资金方" :disabled="isEdit">
          <el-option v-for="(item, index) in fundList" :key="index" :label="item.name" :value="item.code"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="最高利率" prop="interestRate">
        <el-input v-model="form.interestRate" placeholder="请填写最高利率" maxlength="5" :disabled="isEdit"></el-input>%
      </el-form-item>
      <el-form-item label="产品名称" prop="name">
        <el-input v-model="form.name" placeholder="请填写产品名称" maxlength="24" :disabled="isEdit"></el-input>
      </el-form-item>
      <el-form-item label="最高授信额度" prop="quota">
        <el-input v-model="form.quota" placeholder="请填写最高授信额度" maxlength="24" :disabled="isEdit"></el-input>元
      </el-form-item>
      <el-form-item label="还款方式" prop="repayMethod">
        <el-select v-model="form.repayMethod" placeholder="请选择资还款方式" disabled>
          <el-option
            v-for="(item, index) in repayMethodList"
            :key="index"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="授信有效期" prop="creditIndate">
        <el-input
          v-model="form.creditIndate"
          placeholder="请填写授信有效期"
          maxlength="24"
          :disabled="isEdit"
        ></el-input
        >月
      </el-form-item>
      <el-form-item label="结息类型" prop="interestDateType">
        <el-radio-group v-model="form.interestDateType">
          <el-radio :label="item.value" v-for="(item, index) in typeList" :key="index" :disabled="isEdit">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="最长贷款类型" prop="deadLineType">
        <el-radio-group v-model="form.deadLineType">
          <el-radio :label="item.value" v-for="(item, index) in typeList" :key="index" :disabled="isEdit">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="结息周期" prop="interestDate">
        <el-input placeholder="请填写结算周期" v-model="form.interestDate" maxlength="24" :disabled="isEdit"></el-input
        >{{ form.interestDateType === '0' ? '月' : '日' }}
      </el-form-item>
      <el-form-item label="最长贷款周期" prop="deadLine">
        <el-input placeholder="请填写最长贷款周期" v-model="form.deadLine" maxlength="24" :disabled="isEdit"></el-input
        >{{ form.deadLineType === '0' ? '个月' : '日' }}
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="form.status" placeholder="请选择状态" :disabled="isEdit">
          <el-option
            v-for="(item, index) in statusList"
            :key="index"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="推荐星级" prop="recommendStar">
        <el-select v-model="form.recommendStar" placeholder="请选择星级" :disabled="isEdit">
          <el-option v-for="(item, index) in starList" :key="index" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="产品详情" prop="productDetail">
        <ckeditor v-model="form.productDetail" ref="md" :config="config" :readOnly="isEdit"></ckeditor>
      </el-form-item>
      <el-form-item class="btn">
        <!-- 编辑时，不展示保存按钮和取消按钮 -->
        <el-button type="primary" size="small" @click="save()" v-if="!isShowBtns">保存</el-button>
        <el-button type="primary" size="small" @click="edit()" v-if="isShowBtns">编辑</el-button>
        <!-- 当新增/编辑时，取消时返回不可修改状态 -->
        <el-button size="small" @click="cancel()" v-if="isShowCancelBtn">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { STATUS_LIST } from '@/constants/baseModel'
import { twoDecimalPoint, moreThanOneInteger } from '@/utils/validator'

export default {
  name: 'AddEditProduct',
  props: {
    productDetail: Object,
  },
  data() {
    const checkNumberPoint = (rule, value, callback) => {
      if (!twoDecimalPoint(value)) {
        callback(new Error('格式有误，请重新输入!'))
      } else {
        callback()
      }
    }
    const isInt = (rule, value, callback) => {
      if (!moreThanOneInteger(value)) {
        callback(new Error('格式有误，请重新输入!'))
      } else {
        callback()
      }
    }

    return {
      config: {
        toolbar: [
          ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript'],
          ['Undo', 'Redo', '-', 'Find', 'Replace', 'SelectAll', 'RemoveFormat'],
          ['NumberedList', 'BulletedList', 'Form', 'Table', 'HorizontalRule', 'Smiley'],
          ['Preview', 'Maximize', 'Link', 'Unlink', 'Radio', 'Checkbox', 'TextField', 'Textarea'],
          ['Format', 'Font', 'FontSize', 'ShowBlocks'],
          [
            'Styles',
            'Outdent',
            'Indent',
            'Blockquote',
            'JustifyLeft',
            'JustifyCenter',
            'JustifyRight',
            'JustifyBlock',
            '-',
          ],
          ['TextColor', 'BGColor', 'SpecialChar', 'PageBreak'],
        ],
        removePlugins: 'elementspath',
      },
      statusList: STATUS_LIST,
      starList: [
        { label: '一星', value: 1 },
        { label: '二星', value: 2 },
        { label: '三星', value: 3 },
        { label: '四星', value: 4 },
        { label: '五星', value: 5 },
      ],
      //资方列表
      fundList: [],
      typeList: [
        { label: '按月', value: '0' },
        { label: '按日', value: '1' },
      ],
      repayMethodList: [{ label: '随借随还', value: '随借随还' }],
      rules: {
        fundCode: [{ required: true, message: '请选择资金方' }],
        // 最多两位小数
        interestRate: [{ required: true, message: '请填写最高利率' }, { validator: checkNumberPoint }],
        name: [{ required: true, message: '请填写产品名称' }],
        // 最多两位小数
        quota: [{ required: true, message: '请填写最高授信额度' }, { validator: checkNumberPoint }],
        // 整数
        creditIndate: [{ required: true, message: '请填写授信有效期' }, { validator: isInt }],
        // 整数
        interestDate: [{ required: true, message: '请填写结息周期' }, { validator: isInt }],
        // 整数
        deadLine: [{ required: true, message: '请填写最长贷款周期' }, { validator: isInt }],
      },
      form: {
        // // 产品集code
        // productSetCode: this.$route.query.productSetCode || '',
        ...this.productDetail,
        // // 产品id
        // id: '',
        // // 资金方
        // fundCode: '',
        // // 最高利率
        // interestRate: '',
        // // 产品名称
        // name: '',
        // // 最高授信额度
        // quota: '',
        // // 还款方式 -- 目前只有一种随借随还
        // repayMethod: '随借随还',
        // // 授信有效期 -- 月
        // creditIndate: '',
        // // 结息类型 -- 0|月 1|日
        // interestDateType: '0',
        // // 最长贷款周期类型 -- 0|月 1|日
        // deadLineType: '0',
        // // 结息周期
        // interestDate: '',
        // // 最长贷款周期
        // deadLine: '',
        // // 状态
        // status: '1',
        // // 推荐星级
        // recommendStar: null,
        // // 产品详情
        // productDetail: '',
      },
      isNeedEdit: false,
      //默认编辑按钮
      isShowBtns: true,
    }
  },
  watch: {
    productDetail(newVal, oldVal) {
      if (newVal && !newVal.id) {
        this.isShowBtns = false
        this.isNeedEdit = false
        this.form = { ...newVal }
      } else {
        this.form = { ...newVal }
        this.isNeedEdit = false
        this.isShowBtns = true
      }
    },
  },
  computed: {
    /**
     * 1.如果没有id的存在，表示是可以新增
     * 2.如果有id存在并且初始化isNeedEdit为false时(控制是否为编辑)，表示未点击编辑按钮
     * 3.点击编辑按钮时，isNeedEdit变更为true，isEdit也为true，表示可以编辑
     */
    isEdit() {
      return !this.form.id ? false : this.isNeedEdit && this.form.id ? false : true
    },
    isShowCancelBtn() {
      /**
       * 1. 没有id存在时，不需要展示取消按钮
       * 2. 如果触发了isNeedEdit为true时，说明进入编辑状态
       */
      return !this.form.id ? false : this.isNeedEdit ? true : false
    },
  },
  methods: {
    edit() {
      this.isNeedEdit = true
      this.isShowBtns = false
    },
    save() {
      this.$refs['form'].validate(async valid => {
        if (!valid) return
        await this.saveRequest()
        this.$emit('saveSuccess', { isAdd: this.form.id ? false : true })
      })
    },
    cancel() {
      this.isShowBtns = true
      this.isNeedEdit = false
    },
    async saveRequest() {
      const url = this.form.id ? `/products/${this.form.id}/update` : '/products/add'
      const method = this.form.id ? 'put' : 'post'
      await this.$http[method](url, this.form)
      this.isShowBtns = true
    },
    async getFundsList() {
      const res = await this.$http.get('/funds/list')
      this.fundList = res
    },
  },
  mounted() {
    this.getFundsList()
  },
}
</script>

<style lang="scss" scoped>
.btn {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
::v-deep {
  .el-input {
    width: 400px;
  }
  .el-input__inner {
    width: 400px;
  }
  .el-radio-group {
    width: 400px;
  }
  // .el-textarea {
  //   width: 400px;
  // }
}
</style>
